﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;
using System.IO;
using System.Threading;

namespace CheckRenameFolder
{
    class Program
    {
        public static int _iFolderCount = 0;

        public static void sysWriteAppEntry(string strMessage, bool boolConsoleFlag)
        {
            string MUTEX_FILE = @"CheckRenameFolder";
            Mutex mutexFile = null;

            string strFileName = string.Empty;
            string strFolder = string.Empty;

            strFolder = @"c:\Temp";
            if (Directory.Exists(strFolder) == false)
            {
                strFolder = System.Environment.GetEnvironmentVariable(@"TEMP");
            }

            strFileName = @"CheckRenameFolder.Log." + DateTime.Today.ToString("yyyyMMdd") + @".txt";
            strFileName = strFolder + @"\" + strFileName;
            try
            {
                //SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    mutexFile = new Mutex(false, MUTEX_FILE);
                    mutexFile.WaitOne();  //Wait until the file is open

                    using (StreamWriter w = File.AppendText(strFileName))
                    {
                        string strTmp = "\r\n";

                        strTmp += DateTime.Now.ToString("hh:mm:ss");
                        //w.WriteLine("SPSiteCurrentUser.LoginName=" + Convert.ToString(SPSiteCurrentUser.LoginName));
                        if (string.IsNullOrEmpty(strMessage) == false)
                            strTmp += "\t" + strMessage;

                        w.WriteLine(strTmp);
                        if (boolConsoleFlag == true)
                            Console.WriteLine(strTmp);

                        w.Flush();
                        w.Close();
                    }
                }//);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("CheckRenameFolder - Program.cs - No rights to access log folder(" + strFolder + ")! ex.Message = " + ex.Message);
            }
            finally
            {
                if (mutexFile != null)
                {
                    mutexFile.ReleaseMutex();
                }
            }
        }

        public static void checkFolders(DirectoryInfo dirinfo)
        {
            string strFolderName = string.Empty;
            string strNewName = string.Empty;

            strFolderName = dirinfo.Name;
            if (strFolderName.Equals(@"_private", StringComparison.InvariantCultureIgnoreCase)
                || strFolderName.Equals(@"_cts", StringComparison.InvariantCultureIgnoreCase)
                || strFolderName.Equals(@"_catalogs", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (dirinfo.GetDirectories().Length > 0)
            {
                DirectoryInfo[] oSubFolders = dirinfo.GetDirectories();
                foreach (DirectoryInfo objDirectoryInfo in oSubFolders)
                {
                    //compareFiles(string.Format(@"{0}\{1}", strFolderPath, strSubFolderName), string.Format(@"{0}/{1}", strSiteFolderUrl, strSiteSubFolderName));
                    try
                    {
                        checkFolders(objDirectoryInfo);
                    }
                    catch (Exception ex)
                    {
                        sysWriteAppEntry(string.Format(@"ex.message={0}", ex.Message), true);
                    }
                }
            }

            _iFolderCount++;

            if (strFolderName.StartsWith(@"_") == false)
            {
                if (_iFolderCount % 10 == 0)
                {
                    Console.Write(@".");
                }
                return;
            }

            while (strFolderName.StartsWith(@"_"))
            {
                strFolderName = strFolderName.Substring(1) + @"_";
            }
            strFolderName = strFolderName.Trim();

            strNewName = string.Format(@"{0}\{1}", dirinfo.Parent.FullName, strFolderName);
            sysWriteAppEntry(string.Format(@"current name: {0}, new name: {1}", dirinfo.Name, strNewName), true);

            FileAttributes objFileAttributes = dirinfo.Attributes;
            if ((objFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden)
            {
                dirinfo.Attributes = dirinfo.Attributes & ~FileAttributes.Hidden;
                dirinfo.Attributes = dirinfo.Attributes & ~FileAttributes.System;
                dirinfo.MoveTo(strNewName);
            }

        }

        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Now.ToString("hh:mm:ss") + "\t" + "start......");

            DirectoryInfo dirinfo = new DirectoryInfo(@"X:\");

            checkFolders(dirinfo);

            Console.WriteLine(DateTime.Now.ToString("hh:mm:ss") + "\t" + "complete. Press 'enter' to exit.");
            Console.ReadLine();
        }
    }
}
